<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Device;
use Illuminate\Http\Request;

class TagApiController extends Controller
{
    /**
     * 根据设备资产编号获取关联的零件数据及扩展信息
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getPartsByAssetNumber(Request $request)
    {

        // 验证请求参数
        $assetNumber = $request->query('asset_number');

        if (!$assetNumber) {
            return response()->json(['message' => '请提供资产编号 (asset_number)'], 400);
        }

        // 查询设备及其关联数据
       $device = Device::with(['category', 'place', 'parts.partCategory', 'parts.manufacturer'])
        ->where('Asset_Number', $assetNumber)
        ->first();

        if (!$device) {
            return response()->json(['message' => '未找到该资产编号的设备'], 404);
        }

        // 获取零件数据
        $parts = $device->parts;

        // 返回 HTML 视图
        return view('device_tag', [
        'device' => [
            'Asset_Number'     => $device->Asset_Number,
            'name'     => $device->Name,
            'category' => $device->category->category,
            'location' => $device->place->place ?? '未知位置',
            'User_id'     => $device->User_id,
            'State'    => $device->State
        ],
        'parts' => $device->parts // 已包含 partCategory 和 manufacturer 关联
    ]);
    }
}